package n.info.media;


import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImageManager {

	// ~ constants .................................................................................
	// ~ Static fields/initializers .............................................................
	
	private static ImageManager instance ;
	
	// ~ Static methods ........................................................................
	
	public static ImageManager getDefault(){
		if(instance == null){
			instance = new ImageManager() ;
		}
		return instance ;
	}
	
	// ~ Instance fields .........................................................................
	
	private final Map<String, Bitmap> cache = new ConcurrentHashMap<String, Bitmap>();
	
	// ~ Constructors ...........................................................................
	
	private ImageManager() {
	    
    }
	
	// ~ Properties ...............................................................................
	// ~ Abstract methods ...................................................................
	// ~ Abstract methods implementations .......................................
	// ~ Interface implementations ......................................................
	// ~ Methods ..................................................................................	
	
	public void loadBitmapOnThread(final String urlString, final ImageView imageView) {
	    
		if(urlString == null || urlString.isEmpty()){
			imageView.setImageBitmap(null);
		}
		else if(cache.containsKey(urlString)){
			imageView.setImageBitmap(cache.get(urlString));
		}
		else{
			new DownloadTask(urlString, imageView).execute(urlString);
		}
    }
	
	// ~ Inner classes ...........................................................................
	
	private class DownloadTask extends AsyncTask<String, Void, Bitmap>{
		
		final WeakReference<ImageView> ref ;
		
		public DownloadTask(String url, ImageView imageView){
			ref = new WeakReference<ImageView>(imageView);
		}
		
		@Override
        protected Bitmap doInBackground(String... urls) {
			Bitmap bitmap = null ;
            try {
                bitmap = BitmapFactory.decodeStream((InputStream) new URL(urls[0]).getContent());
                cache.put(urls[0], bitmap);
            }
            catch (Exception e) {
            	//TODO handle exception
            }		
            return bitmap;
        }
		
		protected void onPostExecute(Bitmap result) {
			ImageView imageView = ref.get() ;
			if(imageView != null)
				imageView.setImageBitmap(result);
	     }
	}
	
}
